import React, { useEffect, useState } from 'react';
import { ScrollView, Text, TextInput, View, } from "react-native";
import tw from "twrnc";
import Icon from 'react-native-vector-icons/AntDesign';
import { router } from 'expo-router';
import CountryFlag from 'react-native-country-flag';
import { RadioButton, Modal, } from 'react-native-paper';
import TencentCaptcha from '@/components/TencentCaptcha';
import { post } from '@/utils/api';
import NavBar from "@/components/NavBar";
import * as SecureStore from 'expo-secure-store';
import { useNavigation, NavigationProp } from '@react-navigation/native';


type RootStackParamList = {
  'perfect-info': { phoneNumber: string };
};




export default function Register() {
  const navigation = useNavigation<NavigationProp<RootStackParamList>>();
  const goAreaCode = () => {
    // 跳转到选择区号页面
    router.push('/(auth)/area-code')
  }
  const [isChecked, setIsChecked] = useState(false);
  const handleCheckboxChange = () => {
    setIsChecked(!isChecked);
  };

  const [phoneNumber, setPhoneNumber] = useState('');
  const [isRequesting, setIsRequesting] = useState(false); // 控制请求状态，防止重复请求
  const [visible, setVisible] = React.useState(false);
  const [time, setTime] = useState(60);
  const [timer, setTimer] = useState(null);
  const [backendCode, setBackendCode] = useState('');
  const [frontendCode, setFrontendCode] = useState('');
  const showModal = () => {
    if (!phoneNumber) {
      alert("请输入手机号！");
      return;
    }

    if (time === 60) {
      setVisible(true);
    }
  }
  const hideModal = () => setVisible(false);
  const containerStyle = {
    backgroundColor: 'white',
    padding: 10,
    height: 300,
    margin: 50,
    borderRadius: 10,
  };

  const handleCaptchaSuccess = () => {
    setVisible(false); // 关闭模态框
    startTimer(); // 开始倒计时
  };

  // 启动倒计时
  const startTimer = () => {
    setTime(60); // 每次重新获取验证码时重新初始化倒计时为60秒
    getCode()
    // 清除之前的定时器
    if (timer) {
      clearInterval(timer);
    }

    const newTimer = setInterval(() => {
      setTime(prevTime => {
        if (prevTime <= 1) {
          clearInterval(newTimer); // 倒计时结束，清除定时器
          return 60; // 倒计时结束后重置为60秒
        }
        return prevTime - 1; // 每秒减一
      });
    }, 1000);

    setTimer(newTimer); // 保存定时器ID
  };


  const getCode = async () => {
    console.log('Before request');
    try {
      const res = await post('sendCode', { phoneNumber });
      console.log('After request');
      if (res.vcode) {
        setBackendCode(String(res.vcode));
      } else {
        console.error('Invalid response format:', res);
      }
    } catch (error) {
      console.error('Request failed', error);
    }
  }


  /* 协议 */
  const [agreementVisible, setAgreementVisible] = useState(false);

  const showAgreementModal = () => {
    setAgreementVisible(true);
  };

  const hideAgreementModal = () => {
    setAgreementVisible(false);
  };

  const handleAgree = () => {
    setIsChecked(true);
    setAgreementVisible(false);
  }

  const handleDisagree = () => {
    setIsChecked(true);
    setAgreementVisible(false);
  }




  const handleRegister = async () => {
    if (phoneNumber === '') {
      alert("请输入手机号")
      return
    }

    // 检查手机号格式
    if (!/^\d{11}$/.test(phoneNumber)) {
      alert("请输入正确的手机号！");
      return;
    }

    if (frontendCode === '') {
      alert("请输入验证码")
      return
    }
    if (frontendCode ) {
      if (!isChecked) {
        showAgreementModal()
        return
      }

      const userInfo = {
        id: '',
        nickname: '',
        gender: '',
        country: '',
        selectedDate: '',
        language: '',
        avatar: '',
      }
      let userListStr = await SecureStore.getItemAsync('userList')
      let userList = userListStr ? JSON.parse(userListStr) : [];
      let user = userList.find((item: any) => item.phoneNumber === phoneNumber);

      if (user) {
        alert("该手机号已注册！")
        return
      } else {
        userList.push({ ...userInfo, phoneNumber })
        await SecureStore.setItemAsync('userList', JSON.stringify(userList))
        await SecureStore.setItemAsync('phoneNumber', phoneNumber)
        navigation.navigate('perfect-info', { phoneNumber: phoneNumber });
      }
    }
    else {
      alert("验证码错误！")
    }
  }

  useEffect(() => {
    return () => {
      if (timer) {
        clearInterval(timer); // 清理定时器
      }
    };
  }, [timer]); // 组件卸载时清除定时器





  return (
    <View style={tw`flex-1`}>
      <NavBar title="注册" rightElement={true} />
      <View style={tw`flex-1`}>
        <View style={tw`p-4`}>
          <Text style={tw`text-lg font-bold mb-8`} >注册账号</Text>
          <View style={tw`flex-row items-center border-2 border-gray-300 rounded-full my-1.5 px-2`}>
            <CountryFlag isoCode='CN' size={30} style={tw`rounded-full h-5 w-5 mx-3px`} />
            <Text>+86</Text>
            <View style={tw`mx-3px`}>
              <Icon name="caretdown" size={10} color="#4F8EF7" onPress={goAreaCode} />
            </View>
            <TextInput
              style={tw`p-2`}
              placeholder="请输入手机号"
              placeholderTextColor="#999999"
              value={phoneNumber}
              onChangeText={(text) => setPhoneNumber(text)}
            />
          </View>

          <View style={tw`flex-row items-center justify-between  border-2 border-gray-300 rounded-full my-1.5 px-2`}>
            <TextInput
              style={tw`p-2`}
              placeholder="请输入验证码"
              placeholderTextColor="#999999"
              value={frontendCode}
              onChangeText={(text) => setFrontendCode(text)}
            />
            <View>
              <Text style={{ color: '#27EBD7' }} onPress={showModal}>{time === 60 ? '获取验证码' : `${time}s后重新获取`}</Text>
            </View>
          </View>

          <View style={tw`flex-row items-center justify-center my-5`}>
            <View style={tw`flex items-center justify-center bg-gray-200 rounded-full w-16 h-16`}>
              <Icon name="arrowright" size={30} color="#A7ABAA" onPress={handleRegister} />
            </View>
          </View>
        </View>

        <View style={tw`flex-row items-center justify-center absolute bottom-2 left-0 right-0 mx-5`}>
          <RadioButton value={String(isChecked)} status={isChecked ? 'checked' : 'unchecked'}
            onPress={handleCheckboxChange}
            color="#26EBD7" />
          <Text style={tw`text-teal-300`}>《WorldTalks用户协议》</Text>
          <Text>和</Text>
          <Text style={tw`text-teal-300`}>《WorldTalks隐私权政策》</Text>
        </View>


        {/*验证码 */}
        <Modal visible={visible} onDismiss={hideModal} contentContainerStyle={containerStyle}>
          <View style={tw`flex-1 justify-center py-5`}>
            <TencentCaptcha onSuccess={handleCaptchaSuccess}></TencentCaptcha>
          </View>
        </Modal>



        {/*隐私政策与用户协议 */}
        <Modal visible={agreementVisible} onDismiss={hideAgreementModal} contentContainerStyle={containerStyle} >
          <View style={tw`flex-1 justify-center py-2`}>
            <Text style={tw`text-center text-2xl font-bold mb-5`}>隐私政策与用户协议</Text>
            <ScrollView style={tw`px-3`}>
              <Text>亲爱的用户，感谢您信任并使用WorldTalk!</Text>
              <Text>我们依据相关法律法规要求制定了《WorldTalk用户协议》和《WorldTalk隐私权政策》，请您在点击同意前仔细阅读并充分理解相关条款，尤其是以颜色或加粗进行标识的重要条款。为便于您理解《WorldTalk隐私权政策》，特向您说明如下当您注册WorldTalk服务时，我们会收集您的唯一设备识别码(MEVAndroIdID/IDFA/OPENUDID，GUID/IP地址/SIM卡MS信息/ICCID信息)，用于标识您为WorldTalk的用户。如果您使用O0、微信、Facebook、Gooale关联登录WorldTalk，我们会收集您QQ、微信、Facebook 或 Google的唯一标识，用于保存您的登录信息，使您在使用不同设备登录时能够同步您的数数据。在您使用第三方帐号注册或登录后，您的第三方帐号将会与WorldTalk帐号进行绑定。</Text>
              <Text>当您创建WorldTalk ID时，我们会收集您的个人信息，包括性别，年龄，国籍，您的母语和您正在学习的语言，将有助于我们为您提供更好的服务和体验。</Text>
              <Text>我们会收集您的出生日期(年月日)，并保护未成年人的隐私与安全，在App内将成年人和未成年人完全阻绝开，不能相互交流。</Text>
              <Text>我们会收集您的性别信息，旨在帮助用户根据个人偏好筛选合适的语言交流伙伴，有些用户更倾向于选择与自己同性别的语伴沟通，这也是我们的核心功能。</Text>
              <Text>我们会收集您的手机号码，用于校验您的用户信息。手机号码属于敏感信息，收集手机号码是为了满足相关法律法规的网络实名制要求。若您拒绝提供手机号码，则会影响您在WorldTalk上的正常使用。</Text>
            </ScrollView >
            <View style={tw`flex-row items-center justify-center my-2`}>
              <View style={tw`bg-teal-300 p-2 rounded-md w-24 h-10 mx-8px`}><Text style={tw`text-center`} onPress={handleDisagree}>不同意</Text></View>
              <View style={tw`bg-teal-300 p-2 rounded-md w-24 h-10 mx-8px`}><Text style={tw`text-center`} onPress={handleAgree}>同意</Text></View>
            </View>
          </View>
        </Modal>
      </View>
    </View>
  )
}





